<template>
  <div class="data-config">
    <el-button type="primary" @click="handleClick">数据配置</el-button>

    <el-dialog v-model="dialogVisible" append-to-body destroy-on-close title="数据配置" width="80%">
      <el-form ref="formRef" label-width="120px" :model="form">
        <el-form-item class="form-group" label="人大/政协">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="总人数" prop="a.total">
                <el-input v-model="form.a.total" controls-position="right" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="已到人数" prop="a.arrived">
                <el-input v-model="form.a.arrived" controls-position="right" :max="form.a.total" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="未到人数" prop="a.absent">
                <el-input v-model="form.a.absent" controls-position="right" :max="form.a.total" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="请假人数" prop="a.leave">
                <el-input v-model="form.a.leave" controls-position="right" :max="form.a.total" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item class="form-group" label="列席">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="总人数" prop="b.total">
                <el-input v-model="form.b.total" controls-position="right" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="已到人数" prop="b.arrived">
                <el-input v-model="form.b.arrived" controls-position="right" :max="form.b.total" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="未到人数" prop="b.absent">
                <el-input v-model="form.b.absent" controls-position="right" :max="form.b.total" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col> -->
            <el-col :span="8">
              <el-form-item label="请假人数" prop="b.leave">
                <el-input v-model="form.b.leave" controls-position="right" :max="form.b.total" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { reactive, ref, watch } from 'vue'
import Public from '~/src/api/public'

defineOptions({
  name: 'DataConfig',
})

interface GroupData {
  arrived: number
  total: number
  absent: number
  leave: number
}

interface FormData {
  a: GroupData
  b: GroupData
}

interface Props {
  row?: {
    dataJson?: {
      reportStatus?: {
        a: GroupData
        b: GroupData
      }
    }
    key?: string
  }
}

const props = defineProps<Props>()
const emit = defineEmits(['update'])

const dialogVisible = ref(false)
const loading = ref(false)

const defaultFormData = (): FormData => ({
  a: {
    arrived: 0,
    total: 0,
    absent: 0,
    leave: 0,
  },
  b: {
    arrived: 0,
    total: 0,
    absent: 0,
    leave: 0,
  },
})

const form = reactive<FormData>(defaultFormData())

// 更新表单数据的方法
const updateFormData = (data: { a?: GroupData; b?: GroupData }) => {
  if (!data) return

  const { a = defaultFormData().a, b = defaultFormData().b } = data
  console.log('更新表单数据，源数据:', JSON.stringify({ a, b }, null, 2))

  // 使用 reactive 更新以保持响应式
  form.a = {
    arrived: Number(a.arrived ?? 0),
    total: Number(a.total ?? 0),
    absent: Number(a.absent ?? 0),
    leave: Number(a.leave ?? 0),
  }
  form.b = {
    arrived: Number(b.arrived ?? 0),
    total: Number(b.total ?? 0),
    absent: Number(b.absent ?? 0),
    leave: Number(b.leave ?? 0),
  }

  console.log('更新后的表单数据:', JSON.stringify(form, null, 2))
}

// 监听 props 变化，自动更新表单数据
watch(
  () => props.row?.dataJson?.reportStatus,
  (newVal) => {
    if (newVal && dialogVisible.value) {
      console.log('props 数据更新:', JSON.stringify(newVal, null, 2))
      updateFormData(newVal)
    }
  },
  { deep: true, immediate: true }
)

const handleClick = () => {
  console.log('打开弹窗前的初始数据:', JSON.stringify(form, null, 2))
  dialogVisible.value = true

  const reportStatus = props.row?.dataJson?.reportStatus
  console.log('当前 props 数据:', JSON.stringify(reportStatus, null, 2))

  if (reportStatus) {
    updateFormData(reportStatus)
  } else {
    console.log('重置表单数据')
    Object.assign(form, defaultFormData())
  }
}

const handleSubmit = async () => {
  if (!props.row?.key) {
    ElMessage.error('缺少必要的参数')
    return
  }

  try {
    loading.value = true
    const submitData = {
      dataJson: {
        reportStatus: {
          a: Object.keys(form.a).reduce((acc, key) => {
            acc[key] = Number(form.a[key] ?? 0)
            return acc
          }, {} as GroupData),
          b: Object.keys(form.b).reduce((acc, key) => {
            acc[key] = Number(form.b[key] ?? 0)
            return acc
          }, {} as GroupData),
        },
      },
    }

    await Public.editDictionariesApi({
      url: `/api/dictionaries`,
      data: submitData,
      params: props.row.key,
    })

    // console.log('人大数量', submitData.dataJson.reportStatus.a.total，)
    ElMessage.success('保存成功')
    emit('update')
  } catch (error) {
    console.error('提交失败，错误信息:', error)
    console.error('失败时的表单数据:', JSON.stringify(form, null, 2))
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 监听表单数据变化
watch(
  () => form,
  (newVal) => {},
  { deep: true }
)
</script>

<style lang="scss" scoped>
.data-config {
  display: inline-block;
}

.form-group {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;

  :deep(.el-form-item__label) {
    color: #606266;
  }
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
